﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Ninject;
using Tetris.Interfaces;

namespace Tetris.Screens
{
    public class MenuEntry
    {
        private float _selectionFade;
        private IGameManager _gameManager;
        private SpriteFont _font;

        public string Text { get; set; }
        public Vector2 Position { get; set; }
        public Color SelectedColor { get; set; }
        public Color DeselectedColor { get; set; }

        public virtual int Height
        {
            get { return _font.LineSpacing; }
        }

        public virtual int Width
        {
            get { return (int)_font.MeasureString( Text ).X; }
        }

        public event EventHandler<PlayerIndexEventArgs> Selected;

        public MenuEntry( IGameManager gameManager, string text )
        {
            Text = text;
            SelectedColor = Color.Yellow;
            DeselectedColor = Color.White;
            _gameManager = gameManager;
            _font = _gameManager.ServiceLocator.Get<IContentFactory>().MenuFont;
        }

        protected internal virtual void OnSelectEntry( PlayerIndex playerIndex )
        {
            if( Selected != null )
            {
                Selected( this, new PlayerIndexEventArgs( playerIndex ) );
            }
        }

        public virtual void Update( MenuScreenBase screen, bool isSelected, GameTime gameTime )
        {
            float fadeSpeed = (float)gameTime.ElapsedGameTime.TotalSeconds * 4;

            if( isSelected )
            {
                _selectionFade = Math.Min( _selectionFade + fadeSpeed, 1 );
            }
            else
            {
                _selectionFade = Math.Max( _selectionFade - fadeSpeed, 0 );
            }
        }

        public virtual void Draw( IGameManager gameManager, MenuScreenBase screen, SpriteBatch spriteBatch, bool isSelected, GameTime gameTime )
        {
            Color color = isSelected ? SelectedColor : DeselectedColor;

            // Pulsating like a scaled sinus-curve
            float pulsate = (float)Math.Sin( gameTime.TotalGameTime.TotalSeconds * 6 ) + 1;
            float scale = 1 + pulsate * 0.05f * _selectionFade;

            color *= screen.TransitionAlpha;

            Vector2 origin = new Vector2( 0, _font.LineSpacing / 2 );

            spriteBatch.Begin();
            spriteBatch.DrawString( _font, Text, Position, color, 0, origin, scale, SpriteEffects.None, 0 );
            spriteBatch.End();
        }
    }
}
